#!/bin/bash

: "${ISCSIADM_HOST_STRATEGY:=chroot}"
: "${ISCSIADM_HOST_PATH:=iscsiadm}"

echoerr() { printf "%s\n" "$*" >&2; }

case ${ISCSIADM_HOST_STRATEGY} in
  chroot)
    # https://engineering.docker.com/2019/07/road-to-containing-iscsi/
    chroot /host /usr/bin/env -i PATH="/usr/sbin:/usr/bin:/sbin:/bin" ${ISCSIADM_HOST_PATH} "${@:1}"
    ;;

  nsenter)
    # https://github.com/siderolabs/extensions/issues/38#issuecomment-1125403043
    iscsid_pid=$(pgrep --exact --oldest iscsid)
    if [[ "${iscsid_pid}x" == "x" ]]; then
      echoerr "failed to find iscsid pid for nsenter"
      exit 1
    fi
    nsenter --mount="/proc/${iscsid_pid}/ns/mnt" --net="/proc/${iscsid_pid}/ns/net" -- ${ISCSIADM_HOST_PATH} "${@:1}"
    ;;

  *)
    echoerr "invalid ISCSIADM_HOST_STRATEGY: ${ISCSIADM_HOST_STRATEGY}"
    exit 1
    ;;
esac
